package com.small.xx.ai.apidoc.controller;

import com.small.xx.ai.apidoc.dto.ApiInfoRequest;
import com.small.xx.ai.apidoc.dto.ApiInfoResponse;
import com.small.xx.ai.apidoc.service.ApiInfoService;
import com.small.xx.ai.apidoc.service.AppServiceService;
import com.small.xx.ai.apidoc.dto.AppServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * API文档控制器
 */
@Controller
@RequestMapping("/api-doc")
public class ApiDocController {
    
    @Autowired
    private ApiInfoService apiInfoService;
    
    @Autowired
    private AppServiceService appServiceService;
    
    /**
     * 显示API文档主页
     * 
     * @param model 模型对象
     * @return 主页模板
     */
    @GetMapping("/")
    public String index(Model model) {
        List<ApiInfoResponse> apis = apiInfoService.getAllApis();
        model.addAttribute("apis", apis);
        return "api-doc/index";
    }
    
    /**
     * 显示API列表页面
     * 
     * @param model 模型对象
     * @return API列表模板
     */
    @GetMapping("/list")
    public String listApis(Model model) {
        List<ApiInfoResponse> apis = apiInfoService.getAllApis();
        model.addAttribute("apis", apis);
        return "api-doc/list";
    }
    
    /**
     * 显示新增API页面
     * 
     * @return 新增API模板
     */
    @GetMapping("/create")
    public String createApiPage(Model model) {
        // 获取所有应用服务列表
        List<AppServiceResponse> appServices = appServiceService.getAllAppServices();
        model.addAttribute("appServices", appServices);
        return "api-doc/create";
    }
    
    /**
     * 处理新增API请求
     * 
     * @param request API信息请求
     * @param model 模型对象
     * @return 重定向到API列表页面
     */
    @PostMapping("/create")
    public String createApi(@ModelAttribute ApiInfoRequest request, Model model) {
        try {
            ApiInfoResponse response = apiInfoService.createApi(request);
            return "redirect:/api-doc/list";
        } catch (Exception e) {
            model.addAttribute("error", "创建API失败: " + e.getMessage());
            // 重新加载应用服务列表
            List<AppServiceResponse> appServices = appServiceService.getAllAppServices();
            model.addAttribute("appServices", appServices);
            return "api-doc/create";
        }
    }
    
    /**
     * 显示编辑API页面
     * 
     * @param id API ID
     * @param model 模型对象
     * @return 编辑API模板
     */
    @GetMapping("/edit/{id}")
    public String editApiPage(@PathVariable Long id, Model model) {
        ApiInfoResponse api = apiInfoService.getApiById(id);
        if (api == null) {
            model.addAttribute("error", "API不存在");
            return "redirect:/api-doc/list";
        }
        // 获取所有应用服务列表
        List<AppServiceResponse> appServices = appServiceService.getAllAppServices();
        model.addAttribute("api", api);
        model.addAttribute("appServices", appServices);
        return "api-doc/edit";
    }
    
    /**
     * 处理编辑API请求
     * 
     * @param id API ID
     * @param request API信息请求
     * @param model 模型对象
     * @return 重定向到API列表页面
     */
    @PostMapping("/edit/{id}")
    public String editApi(@PathVariable Long id, @ModelAttribute ApiInfoRequest request, Model model) {
        try {
            ApiInfoResponse response = apiInfoService.updateApi(id, request);
            if (response == null) {
                model.addAttribute("error", "API不存在");
                // 重新加载应用服务列表
                List<AppServiceResponse> appServices = appServiceService.getAllAppServices();
                model.addAttribute("appServices", appServices);
                return "api-doc/edit";
            }
            return "redirect:/api-doc/list";
        } catch (Exception e) {
            model.addAttribute("error", "更新API失败: " + e.getMessage());
            // 重新加载应用服务列表
            List<AppServiceResponse> appServices = appServiceService.getAllAppServices();
            model.addAttribute("appServices", appServices);
            return "api-doc/edit";
        }
    }
    
    /**
     * 处理删除API请求
     * 
     * @param id API ID
     * @return 重定向到API列表页面
     */
    @PostMapping("/delete/{id}")
    public String deleteApi(@PathVariable Long id, Model model) {
        try {
            boolean deleted = apiInfoService.deleteApi(id);
            if (!deleted) {
                model.addAttribute("error", "API不存在");
            }
            return "redirect:/api-doc/list";
        } catch (Exception e) {
            model.addAttribute("error", "删除API失败: " + e.getMessage());
            return "redirect:/api-doc/list";
        }
    }
    
    /**
     * 显示API详情页面
     * 
     * @param id API ID
     * @param model 模型对象
     * @return API详情模板
     */
    @GetMapping("/detail/{id}")
    public String apiDetail(@PathVariable Long id, Model model) {
        ApiInfoResponse api = apiInfoService.getApiById(id);
        if (api == null) {
            model.addAttribute("error", "API不存在");
            return "redirect:/api-doc/list";
        }
        
        // 获取关联的应用服务信息
        AppServiceResponse appService = null;
        if (api.getAppServiceId() != null) {
            appService = appServiceService.getAppServiceById(api.getAppServiceId());
        }
        
        model.addAttribute("api", api);
        model.addAttribute("appService", appService);
        return "api-doc/detail";
    }
    
    /**
     * 显示API测试页面
     * 
     * @param id API ID
     * @param model 模型对象
     * @return API测试模板
     */
    @GetMapping("/test/{id}")
    public String testApiPage(@PathVariable Long id, Model model) {
        ApiInfoResponse api = apiInfoService.getApiById(id);
        if (api == null) {
            model.addAttribute("error", "API不存在");
            return "redirect:/api-doc/list";
        }
        
        // 获取关联的应用服务信息
        AppServiceResponse appService = null;
        if (api.getAppServiceId() != null) {
            appService = appServiceService.getAppServiceById(api.getAppServiceId());
        }
        
        model.addAttribute("api", api);
        model.addAttribute("appService", appService);
        return "api-doc/test";
    }
    
    /**
     * 处理API测试请求
     * 
     * @param id API ID
     * @param testParams 测试参数
     * @param model 模型对象
     * @return API测试结果模板
     */
    @PostMapping("/test/{id}")
    @ResponseBody
    public String testApi(@PathVariable Long id, @RequestParam String testParams, Model model) {
        try {
            return apiInfoService.testApi(id, testParams);
        } catch (Exception e) {
            return "测试失败: " + e.getMessage();
        }
    }
    
    /**
     * 处理增强API测试请求
     * 
     * @param id API ID
     * @param testRequest 测试请求参数
     * @return API测试结果
     */
    @PostMapping("/test-advanced/{id}")
    @ResponseBody
    public String testAdvancedApi(@PathVariable Long id, @RequestBody Map<String, Object> testRequest) {
        try {
            return apiInfoService.testAdvancedApi(id, testRequest);
        } catch (Exception e) {
            return "测试失败: " + e.getMessage();
        }
    }
}